package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.EsSendCarDao;
import com.jk.garden1.dao.SendcardDao;
import com.jk.garden1.dao.SubscribeDao;
import com.jk.garden1.entity.SendcardEntity;
import com.jk.garden1.entity.SubscribeEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 发卡管理表
 */
@Service
public class SendcardService {
    @Autowired
    private SendcardDao sendcardDao;
    @Autowired
    private SubscribeDao subscribeDao;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsSendCarDao esSendCarDao;

    /**
     * 查询全部
     */
    public List<SendcardEntity> selectSendcardList() {
        return sendcardDao.selectList(null);
    }
    /**
     * 新增发卡
     */
    public void addSendcard(SendcardEntity sendcardEntity) {
        SubscribeEntity subscribeEntity = new SubscribeEntity();
        subscribeEntity.setVisitantname(sendcardEntity.getName());
        subscribeEntity.setVisitantphone(sendcardEntity.getPhone());
        subscribeEntity.setIntervieweename(sendcardEntity.getIntervieweename());
        subscribeEntity.setIntervieweecompany(sendcardEntity.getIntervieweename());
        subscribeEntity.setSubscribetime(new Date().toLocaleString());
        subscribeEntity.setSubscribestatus("已接受");
        subscribeDao.insert(subscribeEntity);
        sendcardEntity.setStatus("正常");
        sendcardDao.updateById(sendcardEntity);
    }
    /**
     * 停用
     * @param id
     */
    public void updateCardStatus(Integer id) {
        SendcardEntity sendcardEntity = sendcardDao.selectById(id);
        sendcardEntity.setStatus("停用");
        sendcardDao.updateById(sendcardEntity);

    }

    /**
     * 注销
     * @param id
     */
    public void delCardStatus(Integer id) {
        SendcardEntity sendcardEntity = sendcardDao.selectById(id);
        sendcardEntity.setStatus("已注销");
        sendcardDao.updateById(sendcardEntity);
    }
    public void updateCardIdStatus(Integer id) {
        sendcardDao.selectById(id);
    }


    /**
     * 新建索引
     */
    public void create(){
        es.createIndex(SendcardEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<SendcardEntity> list = sendcardDao.selectList(wp);
        list.forEach(a -> {
            esSendCarDao.save(a);
        });
    }


    /**
     * es高亮查询
     * @param sendcard
     * @return
     */
    public List<SendcardEntity> querySendCardList(SendcardEntity sendcard) {
        if (es.indexExists(SendcardEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //卡号精确查
        if(StringUtils.hasText(sendcard.getCardnumber())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("cardnumber",sendcard.getCardnumber()));
        }
        //电话精确查
        if(StringUtils.hasText(sendcard.getPhone())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("phone",sendcard.getPhone()));
        }
        //员工名称模糊查
        if(StringUtils.hasText(sendcard.getName())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("name",sendcard.getName()))
                    .withHighlightFields(new HighlightBuilder.Field("name").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(sendcard.getName())){
            AggregatedPage<SendcardEntity> employeeEntity = es.queryForPage(build, SendcardEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("name", highlightFields.get("name").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<SendcardEntity> list2 = es.queryForList(build, SendcardEntity.class);
            return  list2;
        }
    }
}
